/**
 * All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
 *
 *MpmProjectBidScoreController
 * 评标细则信息表
 *
 * 修改纪录
 * 2022-04-24 版本：1.0 hudeyong 创建。
 * @version 版本：1.0
 * @author 作者：hudeyong
 * 创建日期：2022-04-24
 */

package com.topscomm.mpm.controller;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.ToLongFunction;
import java.util.function.UnaryOperator;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.classmate.util.ResolvedTypeCache.Key;
import com.github.javaparser.printer.lexicalpreservation.Kept;
import com.topscomm.app.pojo.AppPageEntity;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.cbo.pojo.CboExcelExportTaskEntity;
import com.topscomm.cbo.service.ICboExcelExportTaskService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.service.impl.*;
import com.topscomm.mpm.utils.OfficeOperateUtilExpand;
import com.topscomm.pub.util.*;

import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.ParameterCache;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.*;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboAttachmentService;
import com.topscomm.cbo.service.impl.CboAttachmentService;
import com.topscomm.mpm.controller.auto.MpmProjectBidScoreControllerAuto;
import com.topscomm.mpm.pojo.MpmProjectBidFullScoreEntity;
import com.topscomm.mpm.pojo.MpmProjectBidScoreEntity;
import com.topscomm.mpm.pojo.MpmProjectBidScoreFeedBackEntity;
import com.topscomm.mpm.pojo.MpmProjectBidScoreHisEntity;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.pojo.MpmProjectSaleEntity;
import com.topscomm.mpm.pojo.MpmProjectUnBidScoreEntity;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static java.util.stream.Collectors.summingLong;

/**
 * @author: hudeyong
 * @date: 2022-04-24
 * @description:评标细则信息表Controller
 * @modify:
 */
@Slf4j
@RestController
@RequestMapping("mpm/projectBidScore")
public class MpmProjectBidScoreController extends MpmProjectBidScoreControllerAuto implements IMpmProjectBidScoreController {
	@Autowired
	private MpmProjectSaleService mpmProjectSaleService;
	@Autowired
	private MpmProjectService mpmProjectService;
	@Autowired
	private MpmProjectBidFullScoreService mpmProjectBidFullScoreService;
	@Autowired
	private MpmProjectBidScoreHisService mpmProjectBidScoreHisService;
	@Autowired
	private MpmProjectBidScoreFeedBackService mpmProjectBidScoreFeedBackService;
	@Autowired
	private MpmProjectUnBidScoreService mpmProjectUnBidScoreService;
	@Autowired
	private MpmProjectBidScoreService mpmProjectBidScoreService;

	/**
	 * @author: hudeyong
	 * @date: 2022-04-24
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (paraMap.containsKey("qry_projectcode")) {
			String value = paraMap.get("qry_projectcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectcode='{0}'", value);
		}
		if (paraMap.containsKey("qry_type")) {
			String value = paraMap.get("qry_type").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and type='{0}'", value);
		}
		if (paraMap.containsKey("qry_times")) {
			String value = paraMap.get("qry_times").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and times='{0}'", value);
		}
		// 如果来自复盘页，则只看已发布的数据
		if (paraMap.containsKey("qry_fromreview")) {
			Boolean value = ConvertUtil.convertToBoolean(paraMap.get("qry_fromreview"));
			if (value) {
				sql.appendSingle(" and state = 9 ");
			}
		}
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
			{
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		// 审批时可以看所有，其余只能看已发布
		if (paraMap.containsKey("isapproval")) {
			boolean value = ConvertUtil.convertToBoolean(paraMap.get("isapproval"));
			if(!value) {
				sql.appendSingle(" and (state = '9' or usercode = '{0}')",this.getUserBean().getUser().getCode());
			} else {
				sql.appendSingle(" and state = '1'");
			}
		}
		return sql.toString();
	}


	/**
	 * @author: hudeyong
	 * @date: 2022-04-24
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}
	/**
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: fanzhiming
	 * @date: 2021-03-08
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/dataCodeList")
	public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
		Map<String, Object> codeMap = (Map<String, Object>) super.dataCodeList(paraMap).getResult();
		List<Map<String, Object>> enabledList = datacodeCache.getCodeListMap("CboYesNo", "", "sortcode");
		codeMap.put("enabledList", enabledList);
		List<Map<String, Object>> deptCommonCodeList = datacodeCache.getCodeListMap("DeptCommonCodeTrack", "", "sortcode");
		codeMap.put("deptCommonCodeList", deptCommonCodeList);
		List<Map<String, Object>> projectlevelList = datacodeCache.getCodeListMap("MpmProjectLevel", "", "sortcode");
		codeMap.put("projectlevelList", projectlevelList);
		return ResponseResult.ok(codeMap);
	}
	/**
	 *
	 * @description: 提交审批后
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: hudeyong
	 * @date: 2022-04-24
	 * @modify:
	 */
	@Override
	protected void afterSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.afterSubmit(dataMap, paraMap);
		String state = ConvertUtil.convertToString(paraMap.get("state"));
		String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
		String times = ConvertUtil.convertToString(paraMap.get("times"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("update MPMPROJECTBIDSCORE set state = '1' where projectcode = '{0}' and times = '{1}' and state != 9", projectcode,times);
		this.service.updateExecute(sql.toString());
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: hudeyong
	 * @date: 2022-04-24
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交评标细则信息表申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
	}

	/**
	 * @author: hudeyong
	 * @date: 2022-04-24
	 * @param paraMap
	 * @return
	 * @description:获取mpm信息
	 * @modify:
	 */
	@GetMapping(value = "/queryMpmInfo")
	public ResponseResult<Object> queryMpmInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<>();
			String projectid = ConvertUtil.convertToString(paraMap.get("projectid"));
			String times = ConvertUtil.convertToString(paraMap.get("times"));
			MpmProjectSaleEntity mpmProjectSaleEntity = mpmProjectSaleService.queryById(projectid);
			resultMap.put("bidbegindate", mpmProjectSaleEntity.getBidbegindate());
			resultMap.put("bidenddate", mpmProjectSaleEntity.getBidenddate());
			resultMap.put("purchasepattern", ConvertUtil.convertToString(mpmProjectSaleEntity.getPurchasepattern()));
			//无评分细则申请 赋值一二次自评
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" PROJECTCODE = (SELECT PROJECTCODE FROM MPMPROJECT WHERE id= '{0}') and bidscoretimes = '{1}' ", projectid, times);
			List<MpmProjectUnBidScoreEntity> unBidScoreEntities = mpmProjectUnBidScoreService.queryByWhere(sql.toString());
			if(unBidScoreEntities.size()>0) {
				resultMap.put("existbidscoreid", unBidScoreEntities.get(0).getId());
				if (unBidScoreEntities.get(0).getState() == 1 || unBidScoreEntities.get(0).getState() == 9) {
					resultMap.put("existbidscoredisabled", true);
				} else {
					resultMap.put("existbidscoredisabled", false);
				}
			} else {
				resultMap.put("existbidscoredisabled", false);
			}
			return ResponseResult.ok(resultMap);
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @author: hudeyong
	 * @date: 2022-04-24
	 * @param paraMap
	 * @return
	 * @description:获取评分信息
	 * @modify:
	 */
	@GetMapping(value = "/queryScoreApprovalInfo")
	public ResponseResult<Object> queryScoreApprovalInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<>();
			String id = ConvertUtil.convertToString(paraMap.get("id"));
			// 查找最近批次
			MpmProjectBidScoreEntity scoreEntity = this.service.queryById(id);
			String times = scoreEntity.getTimes();
			if("1".equals(times)) {
				resultMap.put("firstedit", true);
				resultMap.put("secondedit", false);
				resultMap.put("secondshow", false);
			} else {
				resultMap.put("firstedit", true);
				resultMap.put("secondedit", true);
				resultMap.put("secondshow", true);
			}
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle("projectcode = (select projectcode from MpmProjectBidScore where id = '{0}')", id);
			List<MpmProjectEntity> mpmProjectEntities = mpmProjectService.queryByWhere(sql.toString());
			if(mpmProjectEntities.size()>0) {
				resultMap.put("projectinfo", mpmProjectEntities.get(0));
			} else {
				throw new Exception("未找到项目信息，请联系管理员");
			}

			return ResponseResult.ok(resultMap);
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @author: hudeyong
	 * @date: 2022-04-24
	 * @param paraMap
	 * @return
	 * @description:secondshow为TRUE,firstedit、secondedit非招标项目为false，招标项目挂网日期前第一次自评可填写，挂网-开标第二次自评可填写
	 * @modify:
	 */
	@GetMapping(value = "/queryScoreInfo")
	public ResponseResult<Object> queryScoreInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = this.service.queryScoreInfo(paraMap);
			return ResponseResult.ok(resultMap);
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/**
	 * @author: houyuhang
	 * @date: 2022-04-26
	 * @param paraMap
	 * @return
	 * @description:获取已超期的评分信息
	 * @modify:
	 */
	@GetMapping(value = "/getOverdueNum")
	public ResponseResult<Object> getOverdueNum(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String planEndDate = simpleDateFormat.format(new Date());
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" {0}.enabled = 1 and {0}.state = 9 and {1} > {0}.{2} and {3} is null and {0}.{4} = '{5}' AND {0}.{2} IS NOT NULL",
					MpmProjectBidScoreEntity.tableName, SQLAdapter.toDateShort(planEndDate),
					MpmProjectBidScoreEntity.FieldPlanenddate, MpmProjectBidScoreFeedBackEntity.FieldSourceid, MpmProjectBidScoreEntity.FieldProjectcode, paraMap.get("projectcode"));
			List<Map<String, Object>> mpmProjectBidScoreEntities = mpmProjectService.queryMapByWhere(sql.toString(), "bidScoreSoonOverdue");
			return ResponseResult.ok(mpmProjectBidScoreEntities);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/**
	 * 审批详情(单表)
	 *
	 * @param paraMap
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	@SneakyThrows
	@GetMapping(value = "/loadMobilePageInfo")
	public ResponseResult<Object> loadMobilePageInfo(@RequestParam(required = false) Map<String, Object> paraMap) throws SQLException, IOException {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		String pageCode = this.service.getDao().getTableName();
		Map<String, Object> myDadaMap = new HashMap<>();
		//查询页面配置的sql语句
		StringBufferProxy sqlForAppPage = new StringBufferProxy();
		StringBufferProxy sqlForAppPageTab = new StringBufferProxy();
		sqlForAppPage.appendSingle("code='{0}' and enabled=1", pageCode);
		//获取页面信息
		AppPageEntity page = appPageService.queryObjectByWhere(sqlForAppPage.toString());
		//获取tab信息
		sqlForAppPageTab.appendSingle("pageid='{0}' and enabled=1", page.getId());
		List<Map<String, Object>> appPageTabList = appPageTabService.queryMapByWhere(sqlForAppPageTab.toString());
		// 获取sourceid对应的记录
		Map<String, Object> mainListData = this.service.queryMapById(paraMap.get("id").toString());
		// 附件相关
		List<Map<String, Object>> attachList = new ArrayList<>();
		List<String> fieldList = new ArrayList<>();
        fieldList.add("filetype");
        fieldList.add("filesize");
        fieldList.add("displayname");
        fieldList.add("sourcetype");
        fieldList.add("id");
        ICboAttachmentService cboAttachmentService = (CboAttachmentService) SpringUtil.getBean("cboAttachmentService");
		// 第一次自评，获取第一次记录
		StringBufferProxy sql = new StringBufferProxy();
		// 审批结束后查看审批详情
		if ("9".equals(ConvertUtil.convertToString(mainListData.get("state")))) {
            if (MpmSystemConst.BidScoreTimes.firstTime.equals(mainListData.get("times"))) {
                sql.appendSingle(" projectcode = '{0}' and times = '{1}' and approvaltimes = '{2}' order by type asc, id asc", ConvertUtil.convertToString(mainListData.get("projectcode")), MpmSystemConst.BidScoreTimes.firstTime, ConvertUtil.convertToString(mainListData.get("approvaltimes")));
                List<Map<String, Object>> firstList = this.service.queryMapByWhere(sql.toString());
                this.service.convertClobToStringBidScore(firstList);
                myDadaMap.put("mainList", firstList);
                sql.clear();
                sql.appendSingle("sourceid = (select id from mpmproject where projectcode = '{0}') and sourcetype in ('MpmProjectBidScoreFirst')",
                        ConvertUtil.convertToString(mainListData.get("projectcode")));
                attachList = cboAttachmentService.queryMapFieldsByWhere(sql.toString(), fieldList);
                myDadaMap.put("attachmentList", attachList);
            }
            // 第二次自评，获取第二次记录
            if (MpmSystemConst.BidScoreTimes.secondTime.equals(mainListData.get("times"))) {
                sql.clear();
                sql.appendSingle(" projectcode = '{0}' and times = '{1}' and approvaltimes = '{2}' and type in ({3}) order by type asc, id asc", ConvertUtil.convertToString(mainListData.get("projectcode")), MpmSystemConst.BidScoreTimes.secondTime, ConvertUtil.convertToString(mainListData.get("approvaltimes")), MpmSystemConst.BidScoreType.firstType + "," + MpmSystemConst.BidScoreType.secondType);
				List<Map<String, Object>> secondList = this.service.queryMapByWhere(sql.toString());
				this.service.convertClobToStringBidScore(secondList);
                myDadaMap.put("secondList", secondList);
                sql.clear();
                sql.appendSingle("sourceid = (select id from mpmproject where projectcode = '{0}') and sourcetype in ('MpmProjectBidScoreSecond')",
                        ConvertUtil.convertToString(mainListData.get("projectcode")));
                attachList = cboAttachmentService.queryMapFieldsByWhere(sql.toString(), fieldList);
                myDadaMap.put("secondattachmentList", attachList);
                sql.clear();
				sql.appendSingle(" projectcode = '{0}' and times = '{1}' and state = 9 and type in ({2}) and targetscore is not null order by type asc, id asc", ConvertUtil.convertToString(mainListData.get("projectcode")), MpmSystemConst.BidScoreTimes.secondTime, MpmSystemConst.BidScoreType.thirdType);
				List<Map<String, Object>> offerList = this.service.queryMapByWhere(sql.toString());
				myDadaMap.put("offerList", offerList);
			}
        }  else {
		    // 审批中单据
            if (MpmSystemConst.BidScoreTimes.firstTime.equals(mainListData.get("times"))) {
                sql.appendSingle(" projectcode = '{0}' and times = '{1}' and state = 1 order by type asc, id asc", ConvertUtil.convertToString(mainListData.get("projectcode")), MpmSystemConst.BidScoreTimes.firstTime);
                List<Map<String, Object>> firstList = this.service.queryMapByWhere(sql.toString());
				this.service.convertClobToStringBidScore(firstList);
                myDadaMap.put("mainList", firstList);
                sql.clear();
                sql.appendSingle("sourceid = (select id from mpmproject where projectcode = '{0}') and sourcetype in ('MpmProjectBidScoreFirst')",
                        ConvertUtil.convertToString(mainListData.get("projectcode")));
                attachList = cboAttachmentService.queryMapFieldsByWhere(sql.toString(), fieldList);
                myDadaMap.put("attachmentList", attachList);
            }
            // 第二次自评，获取第二次记录
            if (MpmSystemConst.BidScoreTimes.secondTime.equals(mainListData.get("times"))) {
                sql.clear();
                sql.appendSingle(" projectcode = '{0}' and times = '{1}' and state = 1 and type in ({2}) order by type asc, id asc", ConvertUtil.convertToString(mainListData.get("projectcode")), MpmSystemConst.BidScoreTimes.secondTime, MpmSystemConst.BidScoreType.firstType + "," + MpmSystemConst.BidScoreType.secondType);
                List<Map<String, Object>> secondList = this.service.queryMapByWhere(sql.toString());
				this.service.convertClobToStringBidScore(secondList);
                myDadaMap.put("secondList", secondList);
                sql.clear();
                sql.appendSingle("sourceid = (select id from mpmproject where projectcode = '{0}') and sourcetype in ('MpmProjectBidScoreSecond')",
                        ConvertUtil.convertToString(mainListData.get("projectcode")));
                attachList = cboAttachmentService.queryMapFieldsByWhere(sql.toString(), fieldList);
                myDadaMap.put("secondattachmentList", attachList);
				sql.clear();
				sql.appendSingle(" projectcode = '{0}' and times = '{1}' and state = 9 and type in ({2}) and targetscore is not null order by type asc, id asc", ConvertUtil.convertToString(mainListData.get("projectcode")), MpmSystemConst.BidScoreTimes.secondTime, MpmSystemConst.BidScoreType.thirdType);
				List<Map<String, Object>> offerList = this.service.queryMapByWhere(sql.toString());
				myDadaMap.put("offerList", offerList);
            }
        }
		//获取页面（约定：app管理页面配置中的页面编码对应controller表名）
		appPageService.getPageInfo(this.service.getDao().getTableName(), myDadaMap);
		return ResponseResult.ok(myDadaMap);
	}

	/**
	 * @author: hdy
	 * @date: 2022-04-26
	 * @param paraMap
	 * @return
	 * @description:判断是否有审核中的自评反馈
	 * @modify:
	 */
	@GetMapping(value = "/queryFeedBackIsApproval")
	public ResponseResult<Object> queryFeedBackIsApproval(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			String sourceid = ConvertUtil.convertToString(paraMap.get("id"));
			sql.appendSingle("sourceid = '{0}' and state in ('1','9') order by id desc",sourceid);
			List<Map<String, Object>> mpmProjectBidScoreFeedBackEntities = mpmProjectBidScoreFeedBackService.queryMapByWhere(sql.toString());
			boolean key = true;
			List<Map<String, Object>> feedbackList = new ArrayList<>();
			Map<String, Object> resultMap = new HashMap<String, Object>();
			for(Map<String, Object> bidScoreFeedBackEntity : mpmProjectBidScoreFeedBackEntities) {
				if(ConvertUtil.convertToInt(bidScoreFeedBackEntity.get("state")) == 1) {
					key = false;
					resultMap.put("feedbackid", ConvertUtil.convertToLong(bidScoreFeedBackEntity.get("id")));
				} else {
					feedbackList.add(bidScoreFeedBackEntity);
				}
			}
			resultMap.put("feedbackList", feedbackList);
			resultMap.put("key", key);
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @author: hdy
	 * @date: 2022-04-26
	 * @param paraMap
	 * @return
	 * @description:判断是否刷新其他的
	 * @modify:
	 */
	@GetMapping(value = "/queryIsRefresh")
	public ResponseResult<Object> queryIsRefresh(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			StringBufferProxy sql = new StringBufferProxy();
			String id = ConvertUtil.convertToString(paraMap.get("id"));
			sql.appendSingle("ordercode = '{0}'", id);
			List<MpmProjectBidScoreEntity> mpmProjectBidScoreEntities = this.service.queryByWhere(sql.toString());
			boolean key = true;
			if(mpmProjectBidScoreEntities.size()>0) {
				String projectcode = mpmProjectBidScoreEntities.get(0).getProjectcode();
				sql.clear();
				sql.appendSingle("SELECT a.BIDSCOREFLAG as flag,b.bidbegindate FROM MPMPROJECT a,MPMPROJECTSALE b WHERE a.PROJECTCODE = '{0}' AND a.id = b.id",
						projectcode);
				List<Map<String, Object>> projectList = this.service.selectExecute(sql.toString());
				if(projectList.size() > 0 && ConvertUtil.convertToInt(projectList.get(0).get("flag")) == 0) {
					Date bidenddate = ConvertUtil.convertToDate(projectList.get(0).get("bidbegindate"));
					if(bidenddate!= null && bidenddate.after(new Date())) {
						// 挂网大于当前
						key = true;
						resultMap.put("type", mpmProjectBidScoreEntities.get(0).getType());
					}
				}
			}
			resultMap.put("key", key);
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @author: hdy
	 * @date: 2022-04-26
	 * @param paraMap
	 * @return
	 * @description:手机端查看评标细则
	 * @modify:
	 */
	@GetMapping(value = "/queryScoreForMobile")
	public ResponseResult<Object> queryScoreForMobile(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			StringBufferProxy sql = new StringBufferProxy();
			String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
			String projectid = "";
			String existbidscore = "";
			if(projectcode == null || projectcode.isEmpty()) {
				projectid = ConvertUtil.convertToString(paraMap.get("projectid"));
				MpmProjectEntity mpmProjectEntity = mpmProjectService.queryById(projectid);
				projectcode = mpmProjectEntity.getProjectcode();
			} else {
				sql.appendSingle("projectcode = '{0}'", projectcode);
				List<MpmProjectEntity> mpmProjectEntities = mpmProjectService.queryByWhere(sql.toString());
				if(mpmProjectEntities.size()==0) {
					throw new ServiceException("没有找到项目信息！");
				}
				projectid = ConvertUtil.convertToString(mpmProjectEntities.get(0).getId());
				existbidscore = ConvertUtil.convertToString(mpmProjectEntities.get(0).getExistbidscore());
				sql.clear();
			}
			sql.appendSingle("projectcode = '{0}' and times in ('1', '2') and state = '9'", projectcode);
			List<MpmProjectBidScoreEntity> mpmProjectBidScoreEntities = this.service.queryByWhere(sql.toString());
			List<MpmProjectBidScoreEntity> listscore1 = new ArrayList<MpmProjectBidScoreEntity>();
			List<MpmProjectBidScoreEntity> listscore2 = new ArrayList<MpmProjectBidScoreEntity>();
			List<MpmProjectBidScoreEntity> listscore3 = new ArrayList<MpmProjectBidScoreEntity>();
			List<MpmProjectBidScoreEntity> listscore4 = new ArrayList<MpmProjectBidScoreEntity>();
			Map<String, String> scorecost = new HashMap<>();
			scorecost.put("targetscore", "");
			for(MpmProjectBidScoreEntity scoreEntity : mpmProjectBidScoreEntities) {
				if("1".equals(scoreEntity.getTimes())) {
					if("1".equals(scoreEntity.getType())) {
						listscore1.add(scoreEntity);
					} else {
						listscore2.add(scoreEntity);
					}
				} else {
					if("1".equals(scoreEntity.getType())) {
						listscore3.add(scoreEntity);
					} else if (MpmSystemConst.BidScoreType.secondType.equals(scoreEntity.getType())) {
						listscore4.add(scoreEntity);
					} else if (MpmSystemConst.BidScoreType.thirdType.equals(scoreEntity.getType())) {
						scorecost.put("targetscore", scoreEntity.getTargetscore());
					}
				}
			}
			Map<String, Object> score1 = calculationScore(listscore1);
			Map<String, Object> score2 = calculationScore(listscore2);
			Map<String, Object> score3 = calculationScore(listscore3);
			Map<String, Object> score4 = calculationScore(listscore4);
			sql.clear();
			sql.appendSingle("projectcode = '{0}'", projectcode);
			List<MpmProjectBidFullScoreEntity> fullScoreEntities = mpmProjectBidFullScoreService.queryByWhere(sql.toString());
			for(MpmProjectBidFullScoreEntity fullScoreEntity : fullScoreEntities) {
				if("1".equals(fullScoreEntity.getTimes())) {
					if("1".equals(fullScoreEntity.getType())) {
						score1.put("fullsocretotal", fullScoreEntity.getTotalfullsocre());
					} else {
						score2.put("fullsocretotal", fullScoreEntity.getTotalfullsocre());
					}
				} else {
					if("1".equals(fullScoreEntity.getType())) {
						score3.put("fullsocretotal", fullScoreEntity.getTotalfullsocre());
					} else {
						score4.put("fullsocretotal", fullScoreEntity.getTotalfullsocre());
					}
				}
			}
			resultMap.put("scorelist1", score1);
			resultMap.put("scorelist2", score2);
			resultMap.put("scorelist3", score3);
			resultMap.put("scorelist4", score4);
			resultMap.put("scorelist5", scorecost);
			resultMap.put("projectid", projectid);
			if ("0".equals(existbidscore)) {
				resultMap.put("existbidscore", "否");
			} else if ("1".equals(existbidscore)) {
				resultMap.put("existbidscore", "是");
			} else {
				resultMap.put("existbidscore", "");
			}
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	private Map<String, Object> calculationScore(List<MpmProjectBidScoreEntity> scoreEntities) {
		Map<String, Object> map = new HashMap<String, Object>();
		double selfscoretotal = 0;
		double targetscoretotal = 0;
		double improvetotalscore = 0;
		double completionscoretotal = 0;
		for(MpmProjectBidScoreEntity scoreEntity : scoreEntities) {
			selfscoretotal += ConvertUtil.convertToDouble(scoreEntity.getSelfscore());
			targetscoretotal += ConvertUtil.convertToDouble(scoreEntity.getTargetscore());
			improvetotalscore += ConvertUtil.convertToDouble(scoreEntity.getImprovescore());
			completionscoretotal += ConvertUtil.convertToDouble(scoreEntity.getCompletionscore());
		}
		map.put("selfscoretotal", selfscoretotal);
		map.put("targetscoretotal", targetscoretotal);
		map.put("improvetotalscore", improvetotalscore);
		map.put("completionscoretotal", completionscoretotal);
		map.put("scoreinfo", scoreEntities);
		return map;
	}

	/**
	 * @author: hdy
	 * @date: 2022-04-26
	 * @param paraMap
	 * @return
	 * @description:更新是否需要评分细则
	 * @modify:
	 */
	@GetMapping(value = "/updateProjectInfo")
	public ResponseResult<Object> updateProjectInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
			String existbidscore = ConvertUtil.convertToString(paraMap.get("existbidscore"));
			String projectname = ConvertUtil.convertToString(paraMap.get("projectname"));
			String times = ConvertUtil.convertToString(paraMap.get("times"));
			// 如果一次自评，修改一二次;二次自评只修改第二次
			if (MpmSystemConst.BidScoreTimes.firstTime.equals(times)) {
				sql.appendSingle("UPDATE MPMPROJECT SET EXISTBIDSCORE = '{0}',EXISTBIDSCORESECOND = '{0}' WHERE PROJECTCODE  = '{1}'",existbidscore,projectcode);
			} else {
				sql.appendSingle("UPDATE MPMPROJECT SET EXISTBIDSCORESECOND = '{0}' WHERE PROJECTCODE  = '{1}'",existbidscore,projectcode);
			}
			this.service.updateExecute(sql.toString());
			return ResponseResult.ok("ok");
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/**
	 * @author: houyuhang
	 * @date: 2022-11-28
	 * @param paraMap
	 * @return
	 * @description:获取评分信息
	 * @modify:
	 */
	@GetMapping(value = "/queryBidApprovalInfo")
	public ResponseResult<Object> queryBidApprovalInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<>();
			String feedBackid = ConvertUtil.convertToString(paraMap.get("id"));
			// 查找最近批次
			MpmProjectBidScoreFeedBackEntity mpmProjectBidScoreFeedBackEntity = mpmProjectBidScoreFeedBackService.queryById(feedBackid);
			String id = ConvertUtil.convertToString(mpmProjectBidScoreFeedBackEntity.getSourceid());
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle("projectcode = (select projectcode from MpmProjectBidScore where id = '{0}')", id);
			List<MpmProjectEntity> mpmProjectEntities = mpmProjectService.queryByWhere(sql.toString());
			if(mpmProjectEntities.size()>0) {
				resultMap.put("projectinfo", mpmProjectEntities.get(0));
			} else {
				throw new Exception("未找到项目信息，请联系管理员");
			}

			return ResponseResult.ok(resultMap);
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	@PostMapping(value = "/insertThirdScore")
	public ResponseResult<Object> insertThirdScore(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			String projectCode = ConvertUtil.convertToString(paraMap.get("projectCode"));
			this.service.insertThirdTimeScoreInfo(projectCode);
			return ResponseResult.ok("保存成功");
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @Description: 初始化历史数据
	 * @Author: mengmeng
	 * @param: paraMap ->
	 * @Return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date: 2022/12/8 10:49
	 * @Version: 1.0
	 **/
	@PostMapping(value = "/initHistoryThirdScore")
	public ResponseResult<Object> initHistoryThirdScore(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			String result = this.service.initHistoryThirdScore();
			return ResponseResult.ok("初始化成功:" + result);
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	@GetMapping(value = "/queryScoreTimes")
	public ResponseResult<Object> queryScoreTimes(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String projectCode = ConvertUtil.convertToString(paraMap.get("projectCode"));
			int result = this.service.queryScoreTimes(projectCode);
			return ResponseResult.ok(result);
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @Description: 初始化历史数据-主表一二三次自评数据
	 * @Author: houyuhang
	 * @Date: 2022/12/14
	 **/
	@PostMapping(value= "/initHistoryBidScoreInfo")
	public ResponseResult<Object> initHistoryBidScoreInfo(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			mpmProjectBidScoreService.initHistoryBidScoreInfo();
			return ResponseResult.ok("历史数据处理完成！");
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/**
	 * @Description: 获取评分细则审批历史
	 * @Author: houyuhang
	 * @Date: 2023/01/13
	 * @Version: 1.0
	 **/
	@GetMapping(value = "/getScoreIdHis")
	public ResponseResult<Object> getScoreIdHis(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			// 获取该项目此次自评中存在submitdate的记录，这种记录存在审批历史
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" enabled = 1 and projectcode = '{0}' and times = '{1}' and submitdate is not null order by submitdate desc ", ConvertUtil.convertToString(paraMap.get("qry_projectcode")), ConvertUtil.convertToString(paraMap.get("qry_times")));
			List<MpmProjectBidScoreEntity> mpmProjectBidScoreEntities = this.service.queryByWhere(sql.toString());
			Map<String, Object> dataMap = new HashMap<>();
			if (CollectionUtil.isEmpty(mpmProjectBidScoreEntities)) {
				dataMap.put("scoreid", 0);
			} else {
				dataMap.put("scoreid", mpmProjectBidScoreEntities.get(0).getId());
			}
			return ResponseResult.ok(dataMap);
		} catch(Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @Description:    导出大容量表格
	 * @Author:         wuyuyang
	 * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date:           10/2/2023 下午2:14
	 * @Version:        1.0
	 **/
	@PostMapping(value = "/exportExcelForScore")
	public void exportExcelForScore(@RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request,
							HttpServletResponse response) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
			String sord = ConvertUtil.convertToString(paraMap.get("sord"));
			String cols = ConvertUtil.convertToString(paraMap.get("cols"));
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(this.service.spellListSql1(paraMap));
			if (!StringUtil.isEmpty(sidx) && !StringUtil.isEmpty(sord)) {
				sql.appendSingle(" order by type asc, {0} {1} ", sidx, sord);
			}
			List<Map<String, Object>> listDataMap = this.service.queryMapByWhere(sql.toString());
			List<Map<String, Object>> listDataMap1 = new ArrayList<Map<String, Object>>();
			// 将评标细则信息表中的clob字段转换为String，获得新的结果集
			for(Map<String, Object> m : listDataMap){
				m.put(MpmProjectBidScoreEntity.FieldScoredescription, ConvertUtil.clobToString((Clob) m.get(MpmProjectBidScoreEntity.FieldScoredescription)));
				m.put(MpmProjectBidScoreEntity.FieldScoringrubric, ConvertUtil.clobToString((Clob) m.get(MpmProjectBidScoreEntity.FieldScoringrubric)));
				listDataMap1.add(m);
			}
			String[] colArray = cols.split(",");
			List<Map<String, Object>> sheetList = new ArrayList<>();
			Map<String, Object> sheetMap = new HashMap<>();
			sheetMap.put("code","1");
			sheetMap.put("name","商务");
			sheetList.add(sheetMap);
			sheetMap = new HashMap<>();
			sheetMap.put("code","2");
			sheetMap.put("name","技术");
			sheetList.add(sheetMap);
			InputStream inStream = exportExeclXlsx(listDataMap1, colArray,sheetList);
			String fileName = "评分细则导出数据.xlsx";
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
			response.setHeader("Access-Control-Expose-Headers", "FileName");
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];
			int len;
			while ((len = inStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}
			inStream.close();
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage(), true);
		}
	}

	public static InputStream exportExeclXlsx(List<Map<String, Object>> listMap, String[] columns, List<Map<String, Object>> sheetList) throws Exception {
		int rowIndex = 0;
		XSSFWorkbook wb = new XSSFWorkbook();
		// 表头格式
		XSSFCellStyle headCellStyle = wb.createCellStyle();
		headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
		headCellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
		XSSFFont font = wb.createFont();
		font.setFontName(I18nUtil.getMessage("tap.common.songti"));
		font.setBold(true);
		headCellStyle.setFont(font);
		// 表行格式
		XSSFCellStyle lineCellStyle = wb.createCellStyle();
		lineCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
		lineCellStyle.setAlignment(HorizontalAlignment.CENTER);
		lineCellStyle.setBorderLeft(BorderStyle.THIN);
		lineCellStyle.setBorderRight(BorderStyle.THIN);
		lineCellStyle.setBorderTop(BorderStyle.THIN);
		lineCellStyle.setBorderBottom(BorderStyle.THIN);
		lineCellStyle.setWrapText(true);
		for(Map<String, Object> sheetMap : sheetList){
			rowIndex = 0;
			// 表头
			XSSFSheet sheet = wb.createSheet(ConvertUtil.convertToString(sheetMap.get("name")));
			XSSFRow row = sheet.createRow(rowIndex++);
			for (int i = 0; i < columns.length; i++) {
				XSSFCell cell = row.createCell(i);
				cell.setCellStyle(headCellStyle);
				String[] kv = columns[i].split(";");
				String value = kv[1];
				cell.setCellValue(value);
			}
			// 表行
			for (Map<String, Object> data : listMap) {
				if(!ConvertUtil.convertToString(data.get("type")).equals(ConvertUtil.convertToString(sheetMap.get("code")))){
					continue;
				}
				row = sheet.createRow(rowIndex++);
				for (int i = 0; i < columns.length; i++) {
					String[] kv = columns[i].split(";");
					String key = kv[0];
					XSSFCell cell = row.createCell(i);
					String value = "";
					if (!StringUtil.isEmpty(key) && data.get(key) != null) {
						if (data.get(key) instanceof Date) {
							value = DateUtil.dateToString((Date) data.get(key));
							cell.setCellValue(value);
						} else if (data.get(key) instanceof BigDecimal || data.get(key) instanceof Double
								|| data.get(key) instanceof Float) {
							Double d = ConvertUtil.convertToDouble(data.get(key));
							cell.setCellValue(d);
						} else {
							value = data.get(key).toString();
							cell.setCellValue(value);
						}
					}
					cell.setCellStyle(lineCellStyle);
				}
			}
			// 自适应列
			int columnCount = columns.length;
			for (int i = 0; i < columnCount; i++) {
				sheet.autoSizeColumn(i);
				int colWidth = sheet.getColumnWidth(i) * 17 / 10;
				if (colWidth < 255 * 256) {
					sheet.setColumnWidth(i, colWidth);
				} else {
					sheet.setColumnWidth(i, 6000);
				}
			}
		}
		// 生成流
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		InputStream is = null;
		try {
			wb.write(os);
			os.flush();
			byte[] content = os.toByteArray();
			is = new ByteArrayInputStream(content);
		} catch (Exception ex) {
			if (os != null) {
				os.close();
				os = null;
			}
			if (wb != null) {
				wb.close();
			}
		}
		return is;
	}


	/**
	 * @Description:    下载导入模板
	 * @Author:         wuyuyang
	 * @Return:         void
	 * @exception:
	 * @Date:           11/2/2023 上午9:34
	 * @Version:        1.0
	 **/
	@PostMapping(value = "/downloadTemplate")
	public void downloadTemplate(@RequestBody Map<String, Object> paraMap,
								 HttpServletRequest request, HttpServletResponse response) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			// 设置文件名字(给要下载文件重命名);
			String fileName = ConvertUtil.convertToString(paraMap.get("fileName"));
			String templateName = ConvertUtil.convertToString(paraMap.get("templateName"));
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource[] resources = resolver.getResources("officeTemplate/" + templateName);
			Resource resource = resources[0];
			InputStream inStream = resource.getInputStream();
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];
			int len;
			while ((len = inStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}
			inStream.close();
		} catch (Exception e) {
			throw new BusinessException(e);
		}
	}
    /**
     * @Description:    导入方法
     * @Author:         wuyuyang
     * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @exception:
     * @Date:           11/2/2023 下午2:47
     * @Version:        1.0
     **/
	@PostMapping(value = "/importExcel")
	public ResponseResult<Object> importExcel(@RequestParam("file") MultipartFile excelFile,
											  @RequestParam(required = false) Map<String, Object> paraMap) {
		// 得到文件流
		File file = FileUtil.multipartFileToFile(excelFile);
		try {
			int records = this.service.dealImportData(paraMap, file);
			return ResponseResult.ok("成功导入" + records + "条数据");
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage(), true);
		}
	}
	/**
	  * 评分细则三阶段自评统计接口
	  * @author xinfushuo
	  * @param
	  * @throws
	  * @return
	  * @date 2023/3/7
	  * @modify
	  */
	@PostMapping(value = "/threePhaseBidScore")
	public ResponseResult<Object> threePhaseBidScore(@RequestBody Map<String,Object> paraMap){
		BaseUtil.decodeSecureMap(paraMap);
		//处理日期及字符串数组参数
		paraMap.forEach((key,value)->{
			if(value instanceof List){
				paraMap.replace(key,  ((List<String> )value).stream().map(s->"'"+s+"'").collect(Collectors.joining(",")));
			} else if (key.contains("Date") && value instanceof String) {
				paraMap.replace(key,SQLAdapter.toDateLong((String) value));
			}
		});
		List<Map<String,Object>> list = this.service.threePhaseBidScore(paraMap);
	    return ResponseResult.ok(list);
	}

	 /**
      * @description:  导出表头合并的excel
      * @author xinfushuo
      * @param paraMap cols 嵌套 jsonArray 表头结构
      * @throws
      * @return
      * @date 2022/4/18
      * @modify
      */
    @PostMapping(value = "/exportNewExcel" )
    public ResponseResult<Object> exportNewExcel(@RequestBody Map<String,Object> paraMap,
                                                 HttpServletRequest request, HttpServletResponse response){
        //此处处理嵌套的cols
        try {
            paraMap.replace("qry_page",false);
            //从前端获取类型
            JSONArray cols = (JSONArray) paraMap.get("cols");
            String fileName = ConvertUtil.convertToString(paraMap.get("fileName"));
            fileName = fileName.length() == 0 ? "导出数据.xlsx" : fileName + ".xlsx";
			//处理前台传参
			//处理日期及字符串数组参数
			paraMap.forEach((key,value)->{
				if(key.contentEquals("cols")){
					return;
				}
				if(value instanceof List){
					paraMap.replace(key,  ((List<String> )value).stream().map(s->"'"+s+"'").collect(Collectors.joining(",")));
				} else if (key.contains("Date") && value instanceof String) {
					paraMap.replace(key,SQLAdapter.toDateLong((String) value));
				}
			});
			List<Map<String,Object>> list = this.service.threePhaseBidScore(paraMap);
			for (int i = 0; i <list.size(); i++) {
				list.get(i).put("index",i+1);
			}
            InputStream inputStream = OfficeOperateUtilExpand.exportExeclXlsxWithMergeHeader(list,cols);
			this.SetHeader(response, fileName);
			OutputStream outStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            inputStream.close();
            //此处return null 因为如果响应体为正常json串 application contenttype 会被覆盖为json 导致导出文件破损
            return null;
        }catch (Exception e){
            return handleControllerException(e);
        }
    }
	/**
      * @description: setHeader for Excel 导出
      * @author xinfushuo
      * @param  fileName 文件命名
      * @return
      * @date 2022/4/20
      * @modify
      */
    private HttpServletResponse SetHeader(HttpServletResponse response,String fileName)  {
        try{
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("istaskexport", "0");
            // 需要添加否则前台得不到istaskexport
            response.setHeader("Access-Control-Expose-Headers", "istaskexport");
            response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            return response;
        }catch (Exception e ){
            throw new ServiceException(e);
        }
    }
	/**
	 * @description:  导入历史项目第三阶段自评
	 * @author houyuhang
	 * @date 2023/4/14
	 * @modify
	 */
	@PostMapping(value = "/addFirstBidScoreHistory")
	public ResponseResult<Object> addFirstBidScoreHistory(@RequestBody Map<String,Object> paraMap) {
		try {
			this.service.addFirstBidScoreHistory(paraMap);
			return ResponseResult.ok("导入成功！");
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}
}
